<template lang="html">
  <article id="views-coach_orders">
    <ul class="coach_orders-header">
      <li
        :class="{ active: index === curIndex }"
        class="header-item"
        v-for="(item, index) in tablist"
        @click="curIndex = index"
      >
        {{item.value}}
      </li>
    </ul>
    <div class="coach_orders-container" @touchmove="touchmove">
      <PullRefresh
        :on-refresh="refreshList"
        :isLock="isPullRefreshLock"
      >
        <OrderList
          :orderList="currentList"
          :status="status"
          :canLoadMore="canLoadMore"
          v-on:onClickItem="goToDetail"
          v-on:loadmore="loadmore"
        ></OrderList>
      </PullRefresh>
    </div>
  </article>
</template>

<script>
import utils from '@/lib/utils'
import superagent from 'superagent'
import authMiddleware from '@/lib/auth-middleware'

const INDEX_TO_STATUS = [
  'remain', 'finish'
]

export default {
  name: 'Page-CoachOrders',
  components: {
    PullRefresh: require('@/components/common_pull_refresh/'),
    OrderList: require('@/components/coach_orders_orders_list'),
  },
  data(){
    return {
      curIndex: 0,
      containerEle: null,
      isPullRefreshLock: true,
      tablist: [
        { value: '待上课' },
        { value: '已完成' },
      ],
      pageMark: {
        0: 1,
        1: 1,
      },//标记每个订单列表当前页数
      loadMoreMark: {
        0: 1,
        1: 1,
      },//标记是否可加载更多
      orderCollection: {
        [INDEX_TO_STATUS[0]]:[],
        [INDEX_TO_STATUS[1]]: [],
      },
      NOW: Math.floor(Date.now()/1000)
    }
  },
  computed: {
    currentList(){
      let idx = this.curIndex
      return this.orderCollection[INDEX_TO_STATUS[idx]]
    },
    currentPage(){
      return this.pageMark[this.curIndex]
    },
    status(){
      let idx = this.curIndex
      return INDEX_TO_STATUS[idx]
    },
    canLoadMore(){
      return this.loadMoreMark[this.curIndex]
    },
  },
  methods: {
    touchmove(){
      let isUpper = this.containerEle.scrollTop == 0
      if(isUpper){
        this.isPullRefreshLock = false
      } else if(!this.isPullRefreshLock){
        this.isPullRefreshLock = true
      }
    },
    goToDetail(detail){
      this.$router.push({ path: `/coach-order/${detail.subjectId}` })
    },
    loadmore(){
      let index = this.curIndex

      this.getCoachOrders(this.$route.params.coach_id, this.status, this.currentPage + 1)()
      .then(data => {
        if(data.records.length > 0){
          //增加页面标记
          this.pageMark[index]++
          //拼接列表
          let preList = this.orderCollection[INDEX_TO_STATUS[index]].slice()
          this.orderCollection[INDEX_TO_STATUS[index]] = preList.concat(data.records)
          //未满10条则表明已加载全部
          if(data.records.length < 10){
            this.resetLoadMoreMark(index)
          }
        } else {
          this.resetLoadMoreMark(index)
        }
      })
    },
    //下拉刷新列表： 1.刷新当前分类列表；2.重置当前分类的canLoadMore与page
    refreshList(){
      return new Promise((resolve, reject) => {
        let index = this.curIndex

        this.$store.dispatch('toggleIsLoading')

        this.getCoachOrders(this.$route.params.coach_id, this.status, this.currentPage)()
        .then(data => {
          resolve()
          this.orderCollection[INDEX_TO_STATUS[index]] = data.records
          this.resetStatus(index)
          this.$store.dispatch('toggleIsLoading')
          this.isPullRefreshLock = true
        })
        .catch(e => {
          reject()
        })
      })
    },
    resetStatus(index){
      this.pageMark[index] = 1
      this.loadMoreMark[index] = 1
    },
    resetLoadMoreMark(index){
      utils.toast('已加载全部课程')
      this.loadMoreMark[index] = 0
    },
    getCoachOrders(id, status, page = 1){
      let self = this,
          key = (status === 'remain' ? 'startAfter' : 'startBefore')
      return utils.requestFactory({
        url: `/api/subject/coach/${id}`,
        type: 'post',
        params: {
          page,
          [key]: self.NOW
        }
      })
    },
  },
  created(){
    Promise.all([
      this.getCoachOrders(this.$route.params.coach_id, INDEX_TO_STATUS[0])(),
      this.getCoachOrders(this.$route.params.coach_id, INDEX_TO_STATUS[1])()
    ])
    .then(collection => {
      this.orderCollection[INDEX_TO_STATUS[0]] = collection[0].records
      this.orderCollection[INDEX_TO_STATUS[1]] = collection[1].records
    })
    .catch(e => {
      console.log(e);
    })
  },
  mounted(){
    this.containerEle = this.$el.querySelector('.coach_orders-container')
  }
}
</script>

<style lang="scss" scoped>
@import "../css/config";
$border-color: #1b1b1f;
$header-height: 70px;
$padding-top: 35px;
$padding-left: 25px;
#views-coach_orders{
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: $padding-top+$header-height+30px $padding-left $padding-top;
  background-color: $common-bg;
  overflow: hidden;
  .coach_orders-header{
    position: absolute;
    top: $padding-top;
    left: $padding-left;
    display: flex;
    flex-flow: row nowrap;
    align-items: center;
    width: 700px;
    height: $header-height;
    line-height: $header-height;
    box-sizing: border-box;
    border: 2px solid $border-color;
    border-radius: 21px;
    overflow: hidden;
    .header-item{
      flex: 1 1 33.3%;
      text-align: center;
      box-sizing: border-box;
      background: #fff;
      &.active{
        color: $common-red;
        background-color: $border-color;
      }
    }
    .header-item:nth-child(2){
      border-left: 2px solid $border-color;
      border-right: 2px solid $border-color;
    }
  }
  .coach_orders-container{
    width: 100%;
    height: 100%;
    overflow: scroll;
  }
}
</style>
